<template>
  <div class="main-container">
    <div class="flex items-center" style="height: 80px" v-show="headerShow">
      <a-form size="small" :model="query" layout="inline">
        <a-form-item label="年份" prop="beginDate">
          <a-year-picker
            v-model="query.beginDate"
            :style="{ width: '180px' }"
            placeholder="选择开始日期"
            class="bacClass"
          />
        </a-form-item>
        <CorporateSectorCascader
          :configCascader="configCascader"
          @changeCascader="changeCascader"
        />
        <a-form-item label="班组" prop="departmentIds">
          <a-cascader
            :options="options"
            :style="{ width: '360px' }"
            v-model="query.departmentIds"
            class="bacClass"
            multiple
            popup-container="html"
          />
        </a-form-item>
      </a-form>
      <div class="my-tool-bar" style="margin-bottom: 5px">
        <a-space>
          <el-button type="primary" :icon="Search" @click="initData">查询</el-button>
          <!-- <el-button pain @click="emit('takebiaoji', 0)" plain>返回主页</el-button> -->
        </a-space>
      </div>
    </div>
    <div class="my-divisders">
      <a-divider orientation="center">
        <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
        <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
      </a-divider>
    </div>
    <div class="flex h-3/6">
      <div ref="bar1" style="width: 50%; height: 100%"></div>
      <div ref="bar2" style="width: 50%; height: 100%"></div>
    </div>
    <div class="flex h-2/6 " style="width: 100%; height: 38%">
      <div ref="bar3" style="width: 100%; height: 100%"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import * as echarts from 'echarts'
  import { onMounted, onUnmounted, ref, reactive } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import dayjs from 'dayjs'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  import { post } from '@/api/http'
  import { Search, EditPen } from '@element-plus/icons-vue'
  let bar1 = ref() //获取2023年疵布率数据的容器
  let bar2 = ref() //获取2023年各班月疵布率数据容器
  let bar3 = ref()
  let myEcharts = echarts
  let chart
  let chart2
  let chart3

  const headerShow = ref<boolean>(true)
  const configCascader = ref<{}>({
    corporateWidth: '200px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '厂区', //公司label
    sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
  })

  //initData初始化接口参数
  let query: any = reactive({
    beginDate: dayjs().format('YYYY'), //当天日期
    planOrderCode: '',
    departmentIds: [],
  })
  let querytemp 
  const options = ref([])

  const changeCascader = (data: any) => {
    const { corporateId, sectorId, sectorLabel, corporateLabel } = data
    query.departmentIds = []
    query.planOrderCode = corporateId
    post({ url: `org/baCompany/getDepartmentTree?companyId=${corporateId} ` }).then((res: any) => {
      if (res.code == 200) {
        options.value = res.data
      }
    })
  }

  const allTitle = '2023年疵布率数据'
  const allData = [0.11, 0.2, 0.01, 0.05, 0.02, 0.11, 0.2, 0.01, 0.05, 0.02, 0.3, 0.1] //2023年疵布率数据
  const banTitle = '2023年各班月疵布率'
  const banData = [
    { list: [0.11, 0.15, 0.09, 0.15, 0.01, 0.17], ban: 'A班' },
    { list: [0.08, 0.05, 0.01, 0.05, 0.02, 0.08], ban: 'B班' },
    { list: [0.18, 0.15, 0.21, 0.25, 0.01, 0.03], ban: 'C班' },
  ] //2023年各班月疵布率数据
  const markData = 0.15 //2023年疵布率数据目标线
  onMounted(() => {  
    
 chart3= myEcharts.init(bar3.value, 'purple-passion')
 chart= myEcharts.init(bar1.value, 'purple-passion')
 chart2= myEcharts.init(bar2.value, 'purple-passion')})

  onUnmounted(() => {
    myEcharts.dispose
  })
  const temp = {
    year: '2023',
    firmId: 33,
    departmentIds: [609],
  }
  const initData = async () => {
    if (!query.beginDate) {
      Message.warning('年份必填！'); 
      return
    }
    if (!query.planOrderCode) {
      Message.warning('厂区必填！'); 
      return
    }
    if (query.departmentIds.length < 1) {
      Message.warning('班组必填！'); 
      return
    }
    chart.clear()
    chart2.clear()
    chart3.clear()
    let res = await post({
      url: 'qms/report/getDefectiveFabricRateOfMonthByDepartmentIds',
      data: 
      {
      year: query.beginDate,
      firmId: query.planOrderCode,
      departmentIds: query.departmentIds
      },
    })
    if(res.data ===null) {
      Message.warning(res.message);
      return
    }
    querytemp = {
      year: query.beginDate,
      firmId: query.planOrderCode,
      departmentIds: query.departmentIds
      },
    initChart(res.data)
  }
 
  const initChart = (data) => {
  
    let { monthTotalList, defectiveTarget, monthInfoList, mouthList } = data
    if (defectiveTarget===null) {
      defectiveTarget = 0
    }
    //allTitle,allData, banTitle,banData, markData
    const shang = []
    const xia = []
    for (var i = 0; i < monthTotalList.length; i++) {
      if (monthTotalList[i] >= defectiveTarget) {
        shang.push((monthTotalList[i] - defectiveTarget).toFixed(2))
        xia[i] = defectiveTarget
      } else {
        xia[i] = monthTotalList[i]
        shang[i] = 0
      }
    }
    const option1={
      title: {
        text: query.beginDate + '年疵布率数据',
        left: 'left',
      },
      backgroundColor: '#fff',
      xAxis: {
        type: 'category',
        data: mouthList,
        boundaryGap: true,
        axisLabel: {
          interval: 0, // 强制显示所有标签
          rotate: 45, // 旋转角度，以防止标签重叠
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          return (
            params[0].name +
            '疵布率:' +
            (parseFloat(params[0].value) + parseFloat(params[1].value)).toFixed(2) +
            '%'
          )
        },
      },
      yAxis: {
        type: 'value',
        min: 0, // y 轴的最小值
        max: 0.4, // y 轴的最大值
      },
      series: [
        {
          name: '实际',
          data: xia,
          type: 'bar',
          smooth: true,
          stack: 'Search Engine',

          itemStyle: {
            normal: {
              color: 'blue',
              label: {
                show: true,
                position: 'top',
                formatter: function (params) {
                  return ''
                },
              },
            },
          },
          markLine: {
            symbol: ['none'],
            name:'mubiao',
            label: {
              show: true,
              offset: [-10, -10],
              textStyle: {
                color: 'red', // 设置字体颜色为红色
                fontSize: 14,
              },

              formatter: function (params) {
                //标签内容
                return '目标' + params.value.toFixed(2) + '%'
              },
            },
            lineStyle: {
              type: 'solid', // 设置线型为实线
              color: 'red', // 设置线的颜色
              width: 1, // 设置线的宽度
            },
            data: [
              {
                yAxis: defectiveTarget,
              },
            ],
          },
        },
        {
          type: 'bar',
          barGap: '0%', // 柱子与柱子之间的距离
          stack: 'Search Engine',
          animationDelay: 800,
          itemStyle: {
            color: 'red',
          },

          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              return monthTotalList[params.dataIndex].toFixed(2) + '%'
            },
          },
          data: shang,
        },
      ],
    }
    const option2 = {
      title: {
        text: query.beginDate + '年各班月疵布率',
        left: 'left',
      },
      legend: {
        show: true,
      },
      backgroundColor: '#fff',
      xAxis: {
        type: 'category',
        data: mouthList,
        boundaryGap: true,
        axisLabel: {
          interval: 0, // 强制显示所有标签
          rotate: 45, // 旋转角度，以防止标签重叠
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}',
      },
      yAxis: {
        type: 'value',
        min: 0, // y 轴的最小值
        max: 0.4, // y 轴的最大值
      },
      series: [],
    }
    
    if (monthInfoList.length > 0) {
      monthInfoList.forEach((item, index) => {
        option2.series.push({
          name: item.department,
          data: item.defectiveList,
          type: 'bar',
          smooth: true,
          itemStyle: {
            normal: {
              label: {
                show: true,
                position: 'top',
                formatter: '{c}' + '%',
              },
            },
          },
        })
        option2.tooltip.formatter += `<br />{a${index}}疵布率: {c${index}}%`
      })
    } else {
      option2.series = []
      Message.warning('无数据！');
    }
    
    chart.setOption(option1)

    chart2.setOption(option2)
    if (defectiveTarget===null) {
      chart.hideMarkLine('mubiao');
    }
    chart2.off('click')
    chart2.on('click', async(params) => {
      if (params.seriesType === 'bar') {
        // 获取点击的柱状图系列索引和数据
        let department = params.seriesName //名字
        let departmentId //所属id
        for (let i in monthInfoList) {
          if (monthInfoList[i].department === department) {
            departmentId = monthInfoList[i].departmentId
            break
          }
        }
        let month = params.dataIndex + 1 //点击的月份
        const obj = {
          month,
          departmentId,
          year: querytemp.year,
          firmId: querytemp.firmId,
        }
        
        let res = await post({
          url: 'qms/report/getDefectiveFabricRateOfDayByDepartmentId',
          data: obj,
        })
        if(res.code === 200){
                initInfoChart(res.data)
        }else{
          Message.warning('获取失败！');
        }
      }
    })
    window.onresize = function () {
      chart.resize()
      chart2.resize()
      
    }

  }
  const initInfoChart = (data)=>{
    
    let {dayList,defectiveList,department} = data
    const chart3option = {
      title: {
        text: department + '月疵布率',
        left: 'left',
      },
      legend: {
        show: true,
      },
      backgroundColor: '#fff',
      xAxis: {
        type: 'category',
        data: dayList,
        boundaryGap: true,
        axisLabel: {
          interval: 0, // 强制显示所有标签
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}日{c}%',
      },
      yAxis: {
        type: 'value',
        min: 0, // y 轴的最小值
        max: 0.4, // y 轴的最大值
      },
      series: [
      {
          type: 'bar',
          barGap: '0%', // 柱子与柱子之间的距离
          itemStyle: {
            color: 'blue',
          },

          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              return params.value.toFixed(2) + '%'
            },
          },
          data: defectiveList,
        },
      ],
    }
    chart3.setOption(chart3option)
    window.onresize = function () {
      chart.resize()
      chart2.resize()
      chart3.resize()
      
    }
  }
</script>

<style scoped>
  .main-container {
    height: 100%;
    background: #fff;
  }
</style>
